// 模拟UniApp程序对象
// Enhanced mock for more comprehensive page testing
let currentPath = 'pages/index/index';
let mockStorage = {};

// Mock page object factory
const createMockPage = (path) => ({
  path: path,
  $: jest.fn().mockImplementation((selector) => {
    return Promise.resolve({
      text: jest.fn().mockResolvedValue(getMockText(selector, path)),
      attribute: jest.fn().mockImplementation((attr) => {
        return Promise.resolve(getMockAttribute(selector, attr, path));
      }),
      style: jest.fn().mockImplementation((styleProp) => {
        return Promise.resolve(getMockStyle(selector, styleProp, path));
      }),
      property: jest.fn().mockImplementation((prop) => {
        return Promise.resolve(getMockProperty(selector, prop, path));
      }),
      tap: jest.fn().mockResolvedValue(true),
      trigger: jest.fn().mockResolvedValue(true),
      nth: jest.fn().mockImplementation((index) => {
        return Promise.resolve({
          $: jest.fn().mockResolvedValue({
            text: jest.fn().mockResolvedValue(`Item ${index}`),
            attribute: jest.fn().mockResolvedValue('mock-class'),
            tap: jest.fn().mockResolvedValue(true)
          }),
          text: jest.fn().mockResolvedValue(`Element ${index}`),
          attribute: jest.fn().mockResolvedValue('mock-attribute'),
          tap: jest.fn().mockResolvedValue(true)
        });
      })
    });
  }),
  $$: jest.fn().mockResolvedValue([]),
  waitFor: jest.fn().mockResolvedValue(true)
});

// Mock text content based on selector and page
function getMockText(selector, path) {
  const textMap = {
    'pages/index/index': {
      '.title': 'Hello',
      '.logo': '',
      'text': 'Hello'
    },
    'pages/menu/menu': {
      '.menu-item-text': '1.SMT外段取作业',
      '.version-text': 'v1.0.1',
      'text': '1.SMT外段取作业'
    },
    'pages/select/select': {
      '.label': '订单NO',
      'text': '订单NO'
    },
    'pages/operator-confirm/operator-confirm': {
      '.label': '作业员ID',
      '.name-text': '张三',
      '.loading-text': '加载中...',
      'text': '作业员ID'
    },
    'pages/delivery-confirm/delivery-confirm': {
      '.status-value': '',
      '.progress-text': '0/2',
      '.label-inline': '订单No:',
      '.value-inline': 'TEST123',
      '.auth-modal-title': '管理员验证',
      '.auth-warning-text': '警告：执行此操作将清除目前为止的登录信息！',
      '.clear-icon': '×',
      'text': '订单No:'
    },
    'pages/smt/smt': {
      'text': 'SMT Page'
    }
  };
  
  return textMap[path]?.[selector] || 'Mock Text';
}

// Mock attributes based on selector
function getMockAttribute(selector, attr, path) {
  if (attr === 'class') {
    if (selector === '.container') return 'container';
    if (selector === '.menu-item') return 'menu-item';
    if (selector === '.content') return 'content';
    return 'mock-class';
  }
  if (attr === 'src') return '/static/logo.png';
  if (attr === 'placeholder') {
    if (selector.includes('order')) return '请扫描订单号';
    if (selector.includes('machine')) return '请扫描实装机ID';
    if (selector.includes('surface')) return '请扫描实装面';
    if (selector.includes('operator')) return '请扫码输入作业员ID';
    return '请扫描';
  }
  if (attr === 'disabled') return path === 'pages/operator-confirm/operator-confirm' ? null : null;
  if (attr === 'focus') return 'true';
  if (attr === 'password') return selector.includes('password') ? 'true' : null;
  return 'mock-value';
}

// Mock styles
function getMockStyle(selector, styleProp, path) {
  // Menu item specific styles
  if (selector === '.menu-item' && styleProp === 'background-color') {
    return 'rgb(255, 255, 255)';
  }
  if (selector === '.menu-item' && styleProp === 'padding') {
    return '20px';
  }
  
  const styleMap = {
    'display': 'flex',
    'flex-direction': 'column',
    'background-color': 'rgb(245, 245, 245)',
    'height': '100vh',
    'padding': '20px',
    'position': 'fixed',
    'bottom': '10px',
    'right': '10px',
    'color': selector.includes('status') && path.includes('delivery') ? 'green' : 'rgb(0, 0, 0)'
  };
  
  return styleMap[styleProp] || 'mock-style';
}

// Mock properties
function getMockProperty(selector, prop, path) {
  if (prop === 'value') return '';
  if (prop === 'tagName') return 'DIV';
  return 'mock-property';
}

global.program = {
  reLaunch: jest.fn().mockImplementation((path) => {
    currentPath = path.startsWith('/') ? path.substring(1) : path;
    return Promise.resolve(createMockPage(currentPath));
  }),
  
  navigateTo: jest.fn().mockImplementation((path) => {
    currentPath = path.startsWith('/') ? path.substring(1) : path;
    return Promise.resolve(createMockPage(currentPath));
  }),
  
  navigateBack: jest.fn().mockImplementation(() => {
    // Simple navigation back logic
    if (currentPath === 'pages/select/select') {
      currentPath = 'pages/menu/menu';
    } else if (currentPath === 'pages/operator-confirm/operator-confirm') {
      currentPath = 'pages/select/select';
    } else if (currentPath === 'pages/delivery-confirm/delivery-confirm') {
      currentPath = 'pages/operator-confirm/operator-confirm';
    } else {
      currentPath = 'pages/index/index';
    }
    return Promise.resolve(createMockPage(currentPath));
  }),
  
  currentPage: jest.fn().mockImplementation(() => {
    return Promise.resolve(createMockPage(currentPath));
  }),
  
  evaluate: jest.fn().mockImplementation((fn, ...args) => {
    try {
      // Create a mock global context for evaluation
      global.getCurrentPages = () => [{
        data: {
          title: 'Hello',
          operatorName: '张三',
          operatorId: 'OP001',
          inputOrderNo: 'TEST123',
          inputMachineId: 'M05',
          inputSurface: 'TOP',
          focusedField: 'orderNo',
          scanHandler: { destroy: jest.fn() },
          focusManager: { destroy: jest.fn() },
          displayPartBatchId: '',
          status: '',
          bomData: {
            partList: [
              { partId: 'PART001-R1', rollNo: 'ROLL001' },
              { partId: 'PART002-C1', rollNo: 'ROLL002' }
            ]
          },
          SMT_CONTENT_TYPES: {
            FORMAT_ERROR_NO_A0P: 'FORMAT_ERROR:缺少A0P分隔符'
          },
          SCAN_RECORDS_KEY: 'smtScanRecords',
          scanBuffer: '',
          scanDelay: 150,
          consecutiveEnterCount: 0,
          lastEnterTime: 0,
          authFailCount: 0,
          submitFailCount: 0,
          forceUpdateFlag: 0
        },
        setData: jest.fn(),
        methods: {},
        getErrorMessage: (errorType) => {
          const messages = {
            'FORMAT_ERROR_NO_A0P': '扫描格式不正确，缺少A0P分隔符',
            'FORMAT_ERROR_EMPTY': '扫描值为空'
          };
          return messages[errorType] || '未知错误';
        },
        navigateToSelect: jest.fn(),
        clearAllFields: jest.fn(),
        fetchOperatorInfo: jest.fn(),
        onStart: jest.fn(),
        handleCacheError: jest.fn(),
        saveSuccessRecord: jest.fn().mockReturnValue(true),
        saveFailureRecord: jest.fn().mockReturnValue(true),
        checkDuplicateLot: jest.fn().mockReturnValue(false),
        getUniquePartCount: jest.fn().mockReturnValue(1),
        prepareSubmissionData: jest.fn().mockReturnValue({
          orderInfo: {},
          successRecords: [],
          failureRecords: []
        }),
        forceUIUpdate: jest.fn(),
        incrementConfirmFailCount: jest.fn(),
        onBackPress: jest.fn().mockReturnValue(true),
        $el: {},
        $options: {},
        route: {}
      }];
      
      return Promise.resolve(fn(...args));
    } catch (error) {
      return Promise.resolve({ error: error.message });
    }
  }),
  
  callUniMethod: jest.fn().mockImplementation((method, params) => {
    if (method === 'setStorage') {
      if (typeof params === 'object' && params.key && params.data) {
        mockStorage[params.key] = params.data;
      }
      return Promise.resolve(true);
    }
    if (method === 'getStorageSync') {
      const key = typeof params === 'string' ? params : params?.key;
      return Promise.resolve(mockStorage[key] || null);
    }
    if (method === 'removeStorage') {
      const key = typeof params === 'object' ? params.key : params;
      delete mockStorage[key];
      return Promise.resolve(true);
    }
    return Promise.resolve({});
  }),
  
  mockUniMethod: jest.fn().mockResolvedValue(true),
  restoreUniMethod: jest.fn().mockResolvedValue(true),
  systemInfo: jest.fn().mockResolvedValue({
    platform: 'android',
    system: 'Android 10',
    version: '1.0.0'
  })
};

// 模拟uni对象
global.uni = {
  showToast: jest.fn(),
  showModal: jest.fn(),
  request: jest.fn(),
  setStorage: jest.fn(),
  getStorageSync: jest.fn(),
  removeStorage: jest.fn()
};

console.log('Mock setup completed for E2E tests');